package game.controller;


import java.util.Timer;
import java.util.TimerTask;

import game.listener.CKeyListener;
import game.logic.AreaModel;
import game.logic.GameModel;
import game.ui.GameDisplay;

public class GameController implements CKeyListener{
	GameModel model = new GameModel();
	GameDisplay display; 
	AreaModel area;
	DeathListener deathListener;
	boolean death = false;
	
	public void bindDisplay(GameDisplay display){
		this.display  =  display;
	}
	
	public void bindAreaModel(AreaModel area){
		this.area  =  area;
	}
	
	public void init(){
		
		
		deathListener = new DeathListener() {
			
			@Override
			public void death() {
				gameOver();
			}
		};

		
		display.init();
		model.bindArea(area);
		

		model.initArea();
		

		model.setDeathListener(deathListener);
		display.setCKeyListener(this);
		
		display();
		startGame();
		display.show();
	
		death = false;
		
		
	}
	
	public void moveRight(){
		model.blockRight();
		display();
	}
	
	public void moveDown(){
		model.blockDown();
		display();
	}
	
	public void moveLeft(){
		model.blockLeft();
		display();
	}
	
	public void rotate(){
		model.blockRotate();
		display();
	}
	
	public void gameOver() {
		death = true;
		display.displayDeath();
	}
	
	public void startGame(){
		update();
	}
	
	int delay = 500;
	public void update(){
		Timer timer = new Timer();
		timer.schedule(new UpdateTask(), delay);
	}
	
	class UpdateTask extends TimerTask{

		@Override
		public void run() {
			moveDown();
			update();
		}
		
	}
	
	
	public void display(){
		display.displayAll(model.iterableArea(),model.iterableBlock());
	}

	@Override
	public void up() {
		rotate();
	}

	@Override
	public void down() {
		moveDown();
	}

	@Override
	public void left() {
		moveLeft();
	}

	@Override
	public void right() {
		moveRight();
	}

	@Override
	public void space() {
		
	}
}
